#include "qdicethread.h"
#include <QTime>
#include <QMutexLocker>

QDiceThread::QDiceThread()
{

}

void QDiceThread::diceBegin(){
    pause = false;
}

void QDiceThread::dicePause(){
    pause = true;
}

void QDiceThread::threadStop(){
    stop = true;
}

void QDiceThread::run(){
    stop = false;
    seq = 0;
    qsrand(QTime::currentTime().msec());
    while(!stop){
        if(!pause){
            QMutexLocker mutexLocker(&mutex); //sample 13-3
            //mutex.lock();//sample 13 - 2
            diceValue = qrand();
            diceValue = (diceValue % 6) + 1;
            seq++;
            //emit newValue(seq, diceValue); //sample 13 - 1
            //mutex.unlock();//sample 13 - 2
        }
        msleep(500);
    }
    quit();
}

bool QDiceThread::readValue(int *m_seq, int *m_diceValue){
    bool result = false;
    if (mutex.tryLock()){ //如果成功锁定
        *m_seq = seq;
        *m_diceValue = diceValue;
        mutex.unlock();
        result = true;
    }
    return result;
}
